<?php
class Router {
    protected $routes = [];
    
    public function add($url, $controller, $action) {
        $this->routes[$url] = [
            'controller' => $controller,
            'action' => $action
        ];
    }
    
    public function dispatch($url, Container $container) {
        if (array_key_exists($url, $this->routes)) {
            $controllerName = $this->routes[$url]['controller'];
            $action = $this->routes[$url]['action'];
            
            try {
                // 使用容器的控制器工厂创建控制器实例
                $controllerFactory = $container->make('ControllerFactory');
                $controllerInstance = $controllerFactory($controllerName);
                
                if (method_exists($controllerInstance, $action)) {
                    // 调用控制器方法
                    $controllerInstance->$action();
                } else {
                    throw new Exception("方法 {$action} 不存在");
                }
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        } else {
            echo "路由 {$url} 不存在";
        }
    }
}
?>